package example.documentbased.editorModule.controller
{
	import example.documentbased.editorModule.models.EditorModuleModel;
	import example.documentbased.editorModule.views.popUps.OpenDocumentPopUp;
	import example.documentbased.mainModule.controller.ICommonController;
	import example.documentbased.mainModule.models.vo.DocumentVO;
	import example.documentbased.mainModule.models.vo.EditorVO;
	
	import flash.events.Event;
	
	import mx.collections.ArrayList;
	
	import org.etherframework.controller.ReactiveCommand;
	import org.etherframework.controller.common.PopUpModel;
	
	import raix.reactive.IObservable;
	
	public class SelectDocumentCommand extends ReactiveCommand
	{
		private var _editorModel:EditorModuleModel;
		private var _commonController:ICommonController;
		private var _editorController:IEditorController;
		private var _editor:EditorVO;
		
		public function SelectDocumentCommand(editorModel:EditorModuleModel, 
											  commonController:ICommonController, 
											  editorController:IEditorController)
		{
			_editorModel = editorModel;
			_commonController = commonController;
			_editorController = editorController;
			markAsInitialized();
		}
		
		override public function observable():IObservable
		{
			_editor = _editorModel.editor;
			var docsToOpen:ArrayList = getFilteredDocuments();
			var popUpModel:PopUpModel = new PopUpModel("Select Document(s)", docsToOpen);
			
			return _commonController.getShowPopUpCommand(OpenDocumentPopUp, popUpModel).observable()
			.mapMany(function(event:Event):IObservable
			{
				if (event.type == Event.COMPLETE)
				{
					var popUp:OpenDocumentPopUp = OpenDocumentPopUp(popUpModel.popUp);
					var selected:Vector.<Object> = popUp.selectedItems.reverse();
					var document:DocumentVO;
					
					for (var i:int = 0; i < selected.length; i++) 
					{
						document = DocumentVO(selected[i]);
						_editorModel.openDocument(document);
					}
				}
				
				return _editorController.getSetCurrentDocumentCommand(document).observable();
			});
		}
		
		private function getFilteredDocuments():ArrayList
		{
			var result:ArrayList = new ArrayList();
			var savedDocs:ArrayList = _editor.documents;
			var openedDocs:ArrayList = _editorModel.openedDocuments;
			var savedDocument:DocumentVO;
			var openedDocument:DocumentVO;
			
			savedLoop:for (var i:int = 0; i < savedDocs.length; i++) 
			{
				savedDocument = savedDocs.getItemAt(i) as DocumentVO;
				
				for (var j:int = 0; j < openedDocs.length; j++) 
				{
					openedDocument = openedDocs.getItemAt(j) as DocumentVO;
					
					if (openedDocument.id == savedDocument.id)
					{
						continue savedLoop;
					}
				}
				result.addItem(savedDocument);
			}
			
			return result;
		}
	}
}